package com.aispeech.aitv.camera;


import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import java.io.File;
import java.io.FileOutputStream;

/**
 * @author rain  01.12 2018
 */

public class CameraUtils {

    private final String TAG = "CameraUtils";

    private static CameraUtils mInstance;
    private Camera mCamera;

    private String FILE_PATH = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
    private String PICTURE_NAME = "WxSharePhoto.jpg";//System.currentTimeMillis() + ".jpg";

    private CameraUtils() {
    }

    public static CameraUtils getInstance() {
        if (null == mInstance) {
            mInstance = new CameraUtils();
        }
        return mInstance;
    }

    public Camera initCamera() {
        mCamera = Camera.open(1);

        Camera.Parameters parameters = mCamera.getParameters();
        //对焦的方式
        parameters.setFocusMode(Camera.Parameters.ANTIBANDING_AUTO);
        //照片的类型
        parameters.setPictureFormat(ImageFormat.JPEG);

        return mCamera;
    }

    /**
     * 获取自拍照片
     * @return 自拍照片文件
     */
    public File getPhotoFile() {
        File pf = new File(FILE_PATH + PICTURE_NAME);
        if (pf.exists()) {
            return pf;
        }
        return null;
    }

    /**
     * 拍照
     *
     * @return 是否拍照成功
     */
    public void takePhoto(final TakePhotoResultListener listener) {
        if (null != mCamera) {
            //对焦监听
            mCamera.autoFocus(new Camera.AutoFocusCallback() {
                @Override
                public void onAutoFocus(boolean success, Camera camera) {
                    //对焦成功
                    if (success) {
                        try {
                            camera.takePicture(null, null, new PictureCallback() {
                                @Override
                                public void onPictureTaken(byte[] bytes, Camera camera) {
                                    Log.d(TAG, "onPictureTaken: ");
                                    mCamera.startPreview();
//                                    startPreview();//java.lang.RuntimeException: takePicture failed

                                    mCamera.takePicture(new ShutterCallback() {
                                        @Override
                                        public void onShutter() {
                                            //正在拍照
                                            Log.d(TAG, "onShutter: ");
                                        }
                                    }, new PictureCallback() {
                                        @Override
                                        public void onPictureTaken(byte[] bytes, Camera camera) {
                                            //返回未经压缩的RAW类型照片
                                            Log.d(TAG, "onPictureTaken: ");
                                        }
                                    }, new PictureCallback() {
                                        @Override
                                        public void onPictureTaken(byte[] data, Camera camera) {
                                            //返回经过压缩的JPEG类型照片
                                            Log.d(TAG, "onPictureTaken: ");

                                            File file = new File(FILE_PATH, PICTURE_NAME);
                                            try {
                                                //存到本地相册
                                                FileOutputStream fileOutputStream = new FileOutputStream(file);
                                                fileOutputStream.write(data);
                                                fileOutputStream.close();

                                                //显示图片
                                                BitmapFactory.Options options = new BitmapFactory.Options();
                                                options.inSampleSize = 2;
                                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
//                                                mImvShowPhoto.setImageBitmap(bitmap);

//                                                float[] floats = new float[]{1f, 0f, 0f, 0f, -1f, 0f, 0f, 0f, 1f};//竖直翻转
                                                float[] floats = new float[]{-1f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 1f};

                                                Matrix matrix = new Matrix();
                                                matrix.setValues(floats);
//                                                mImvShowPhoto
//                                                    .setImageBitmap(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true));
                                                listener.success(Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true));
                                                //从新开启预览
//                                                startPreview();
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                                listener.failed("拍照失败了!");
                                            }
                                        }
                                    });
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            listener.failed("拍照失败了!");
                        }
                    } else {
                        Log.d(TAG, "onAutoFocus: 获取聚焦失败");
                        listener.failed("获取聚焦失败!");
                    }
                }
            });
        } else {
            Log.e(TAG, "takePhoto: the camera is null !");
            listener.failed("当前的相机出了点问题哦!");
        }
    }


    /**
     * 相机预览
     */
    public void startPreview(SurfaceHolder sfh) {
        try {
            //相机与SurfaceView进行绑定
            mCamera.setPreviewDisplay(sfh);
            //预览的图片旋转
            //mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface TakePhotoResultListener {

        void success(Bitmap bitmap);

        void failed(String errInfo);
    }

}
